using cfg;
using Luban;
using SimpleJSON;
using System;
using YooAsset;
using UnityEngine;
using Panty;
namespace Panty.Test
{
    public interface ILubanInitModule : IModule
    {
        Tables tables { set; get; }
        bool InitSingle();
    }
    public class LubanInitModule : AbsModule, ILubanInitModule
    {
         public Tables tables { set; get; }
        protected override void OnInit()
        {
   
        }


        bool ILubanInitModule.InitSingle()
         {
            Debug.Log("MeowluabanMain  InitSingle");
            var tablesCtor = typeof(cfg.Tables).GetConstructors()[0];
            var loaderReturnType = tablesCtor.GetParameters()[0].ParameterType.GetGenericArguments()[1];

            // 根据cfg.Tables的构造函数的Loader的返回值类型决定使用json还是ByteBuf Loader
            System.Delegate loader = loaderReturnType == typeof(ByteBuf) ?
                new Func<string, ByteBuf>(LoadByteBuf)
                : (System.Delegate)new Func<string, JSONNode>(LoadJson);
            tables = (cfg.Tables)tablesCtor.Invoke(new object[] { loader });
            if (tables!=null)
            {
                return true;
            }
            return false;
        }

        private ByteBuf LoadByteBuf(string files)
        {
            var Packegs = YooAssets.GetPackage("DefaultPackage");
            var ByteBufjsons = Packegs.LoadAssetSync<TextAsset>($"{files}");
            ByteBufjsons.Release();
            return new ByteBuf((ByteBufjsons.AssetObject as TextAsset).bytes);
        }

        private JSONNode LoadJson(string files)
        {
            Debug.Log("当前名称:" + files);
            var Packegs = YooAssets.GetPackage("DefaultPackage");
            var jsons = Packegs.LoadAssetSync<TextAsset>($"{files}");
            Debug.Log("jsons:" + jsons.AssetObject.name);
            //jsons.Release();
            return JSON.Parse((jsons.AssetObject as TextAsset).text);
        }

    }
}